package pkg

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
	"os"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func OssImage(file *multipart.FileHeader, filename string) string {
	client, err := oss.New("oss-cn-beijing.aliyuncs.com", "LTAI5t5hLz4jRqTc5Ab3ZApk", "AmJdU4wrxRr6eGXUY1sfzTznofOsMq")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	bucket, err := client.Bucket("sudyoss")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	open, err := file.Open()
	if err != nil {
		return ""
	}

	format := time.Now().Format("2006-01-02")

	filename = format + filename

	all, err := io.ReadAll(open)
	if err != nil {
		return ""
	}

	defer open.Close()

	// 带进度条的上传。
	err = bucket.PutObject(filename, bytes.NewReader(all))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	return "https://sudyoss.oss-cn-beijing.aliyuncs.com/" + filename
}
